package bb.lanxing.util;

import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FileDownloadUtils {
    private static final int TIMEOUT = 10; // 超时时间，单位：秒

    public static void downloadFile(String fileUrl, String savePath, DownloadProgressListener listener) {
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).writeTimeout(TIMEOUT, TimeUnit.SECONDS).build();

        Request request = new Request.Builder().url(fileUrl).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            long contentLength = response.body().contentLength();
            try (InputStream inputStream = response.body().byteStream(); FileOutputStream outputStream = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    if (listener != null) {
                        int progress = (int) ((totalBytesRead * 100) / contentLength);
                        listener.onProgress(progress);
                    }
                }
                Log.e("file download", "文件下载成功，保存路径: " + savePath);
                if (listener != null) {
                    listener.onComplete();
                }
            }
        } catch (IOException e) {
            Log.e("file download", "文件下载失败: " + e.getMessage());
            e.printStackTrace();
            if (listener != null) {
                listener.onError(e.getMessage());
            }
        }
    }

    public interface DownloadProgressListener {
        void onProgress(int progress);

        void onComplete();

        void onError(String errorMessage);
    }
}
